// This class is written to handle basic animation item with default canvas
$dh.Require(["util/event.js","util/animation.js","ctrl/richcanvas.js"]);
$dh.newClass("DHAnimItem", DHRichCanvas, {
    init: function(container, props) {
        DHRichCanvas.prototype.init.apply(this, [container, props]);
        this.setDefaults(props);
        this.setAnimation();
        this.show(false);
        this.draw(props);
    },
    setDefaults: function(props) {
        this.animStart = props;
        this.canvas.style.position = "absolute";
        this.canvas.style.fontSize = "12px";
        // By default, all given options will become Item's properties 
        $dh.set(this.animDelta, this.animStart);
    },
    // Default draw method
    draw: function(des, time, proc) {
        if ($dh.isNone(time)) {
            if ($dh.isNone(des)) // On animation
                des = {};
            for (var p in this.animStart) // For redraw at anytime
                if ($dh.isNone(des[p]))
                des[p] = this[p];
            this.setProps(des);
        }
        else {
            this.setAnimation(des, time, proc);
            this.animation.start();
        }
    },

    setAnimation: function(des, time, procFunc) {
        if (!this.animation) {
            this.animation = new DHMotion(this.canvas, procFunc || DHMotion.AnimEffects.strongEaseOut);
            // Val is percentage
            var self = this;
            this.animation.setPropValue = function(val) {
                for (var p in self.animDelta)
                    self[p] = Math.floor(self.animStart[p] + self.animDelta[p] * val / 100);
                self.draw();
                self.onAnimation(val);
                self.raise("onanimation", val);
            }
            this.animation.addEv("onstart", function() { self.show(true); self.onAnimStart(); self.raise("onanimstart"); });
            this.animation.addEv("onstop", function() { self.onAnimStop(); self.raise("onanimstop"); });

            this.animation.ownerObj = this;
            // Memory leak preventing
            $dh.addEv(window, "unload", function() {
                if (self && self.animation && self.animation.owner)
                    delete self.animation.ownerObj;
            });
        }

        this.animation.setParams(procFunc || DHMotion.AnimEffects.strongEaseOut, 0, 100, time);
        this.animDelta = {};
        this.animStart = {};
        for (var p in des) {  // Save animation's start status & calculate difference
            this.animStart[p] = this.getProp(p);
            this.animDelta[p] = des[p] - this.animStart[p];
        }
    },
    onAnimation: function() { },
    onAnimStart: function() { },
    onAnimStop: function() { }
});